<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="toggle" label-width="68px">
            <el-form-item label="歌曲名称" prop="songId">
                <el-select v-model="queryParams.songId" placeholder="请选择歌曲" filterable :filter-method="filterSongs"
                    @clear="handleClear">
                    <el-option v-for="song in songOptions" :key="song.id" :label="song.name" :value="song.id" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                    @click="handleDelete">删除
                </el-button>
            </el-col>
            <div class="right-toolbar">
                <el-tooltip class="item" effect="dark" :content="toggle ? '隐藏搜索' : '显示搜索'" placement="top">
                    <el-button size="mini" circle icon="el-icon-search" @click="toggle = !toggle" />
                </el-tooltip>
                <el-tooltip class="item" effect="dark" content="刷新" placement="top">
                    <el-button size="mini" circle icon="el-icon-refresh" @click="getList" />
                </el-tooltip>
            </div>
        </el-row>

        <el-table v-loading="loading" :data="commentData" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="评论ID" align="center" prop="id" width="120" sortable />
            <el-table-column label="评论内容" align="left" prop="content" width="500" show-overflow-tooltip>
                <template slot-scope="scope">
                    <span v-if="scope.row.itId !== 0" class="sub-comment">
                        <span class="reply-to">回复 @{{ getReplyToUser(scope.row) }}：</span>
                        {{ scope.row.content }}
                    </span>
                    <span v-else>{{ scope.row.content }}</span>
                </template>
            </el-table-column>
            <el-table-column label="歌曲名称" align="center" width="120">
                <template slot-scope="scope">
                    {{ songMap[scope.row.songId] || '未知歌曲' }}
                </template>
            </el-table-column>
            <el-table-column label="用户信息" align="center" width="150">
                <template slot-scope="scope">
                    <div class="user-info">
                        <el-avatar :size="30" :src="base_api + scope.row.user.avatar"></el-avatar>
                        <span>{{ scope.row.user.username }}</span>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>
</template>

<script>
import { getCommentList, deleteComment } from "@/api/comment";
import { getMusicList } from "@/api/song";

const BASE_API = process.env.VUE_APP_BASE_API;

export default {
    name: "Comment",
    data() {
        return {
            base_api: BASE_API,
            loading: false,
            ids: [],
            multiple: true,
            toggle: true,
            commentList: [],
            songOptions: [],
            songMap: {},
            queryParams: {
                songId: undefined,
                itId: 0
            }
        };
    },
    computed: {
        commentData() {
            const result = [];
            this.commentList.forEach(comment => {
                result.push(comment);
                if (comment.childComments) {
                    result.push(...this.flattenComments(comment.childComments));
                }
            });
            return result;
        }
    },
    created() {
        const songId = this.$route.query.songId;
        if (songId) {
            this.queryParams.songId = parseInt(songId);
        }
        this.getList();
        this.getSongList();
    },
    methods: {
        flattenComments(comments) {
            const result = [];
            comments.forEach(comment => {
                result.push(comment);
                if (comment.childComments) {
                    result.push(...this.flattenComments(comment.childComments));
                }
            });
            return result;
        },
        getList() {
            this.loading = true;
            getCommentList(this.queryParams).then(response => {
                this.commentList = response.data.list;
                this.loading = false;

                const songIds = new Set();
                this.commentList.forEach(comment => {
                    songIds.add(comment.songId);
                    if (comment.childComments) {
                        comment.childComments.forEach(child => {
                            songIds.add(child.songId);
                        });
                    }
                });

                if ([...songIds].some(id => !this.songMap[id])) {
                    this.getSongList();
                }
            });
        },
        handleQuery() {
            this.getList();
        },
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id);
            this.multiple = !selection.length;
        },
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$confirm('是否确认删除评论编号为"' + ids + '"的数据项？').then(function () {
                return deleteComment(ids);
            }).then(() => {
                this.getList();
                this.$message.success("删除成功");
            }).catch(() => { });
        },
        getReplyToUser(comment) {
            const parentComment = this.findParentComment(comment.itId);
            return parentComment ? parentComment.user.username : '未知用户';
        },
        findParentComment(itId) {
            for (const comment of this.commentList) {
                if (comment.id === itId) return comment;
                if (comment.childComments) {
                    const found = this.findCommentInChildren(comment.childComments, itId);
                    if (found) return found;
                }
            }
            return null;
        },
        findCommentInChildren(comments, itId) {
            for (const comment of comments) {
                if (comment.id === itId) return comment;
                if (comment.childComments) {
                    const found = this.findCommentInChildren(comment.childComments, itId);
                    if (found) return found;
                }
            }
            return null;
        },
        getSongList() {
            getMusicList().then(response => {
                const songList = response.data.list;
                this.songOptions = songList;
                this.songMap = {};
                songList.forEach(song => {
                    this.songMap[song.id] = song.name;
                });
            });
        },
        filterSongs(query) {
            if (query !== '') {
                this.songOptions = this.songOptions.filter(song => {
                    return song.name.toLowerCase()
                        .indexOf(query.toLowerCase()) > -1;
                });
            }
            this.getSongList();
        },
        handleClear() {
            this.queryParams.songId = undefined;
            this.handleQuery();
        }
    }
};
</script>

<style scoped>
.user-info {
    display: flex;
    align-items: center;
    justify-content: center;
}

.user-info span {
    margin-left: 10px;
}

.right-toolbar {
    float: right;
}

.reply-to {
    color: #409EFF;
    margin-right: 5px;
}

.sub-comment {
    padding-left: 20px;
    position: relative;
}

.sub-comment::before {
    content: '';
    position: absolute;
    left: 8px;
    top: 50%;
    width: 4px;
    height: 4px;
    background: #409EFF;
    border-radius: 50%;
}

/* 添加下拉框样式 */
.el-select {
    width: 240px;
}
</style>
